const db = require("../db/index")
const moment = require("moment")

const getOrderTotalNum = (req, res) => {
    let sql = "select count(8) as total from sp_order"
    if (req.query.searchContent !== '')
        sql += ` where order_number like '%${req.query.searchContent}%'`
    db.query(sql, (err, result) => {
        if (err) return res.sendErr(err)
        if (result.length === 0) return res.sendErr("订单数目查找失败!")
        res.send({
            status: 200,
            message: "订单数目查找成功！",
            total: result[0].total
        })
    })
}

const getOrderList = (req, res) => {
    //currentPage pageNum search
    console.log(req.query);
    startNum = (req.query.currentPage - 1) * (req.query.pageNum - 0) // 开始的条数
    let sql = ''
    console.log(req.query.searchContent);
    if (req.query.searchContent === '')
        sql = `select * from sp_order limit ${startNum},${req.query.pageNum - 0}`   // 开始的数目 每页条数
    else
        sql = `select * from sp_order where order_number like '%${req.query.searchContent}%' limit ${startNum},${req.query.pageNum - 0}`

    db.query(sql, (err, result) => {
        if (err) return res.sendErr(err)
        result.forEach(item => {
            item.create_time = moment(item.create_time * 1000).format("YYYY-MM-DD hh:mm:ss")
        });
        res.send({
            status: 200,
            message: "获取订单数据成功!",
            data: result
        })
    })
}

//更改订单信息
const editOrderInfo = (req, res) => {
    console.log(req.body);
    //order_price  order_pay  is_send
    let sql = `update sp_order set ? where order_id = ?`
    db.query(sql, [req.body, req.body.order_id], (err, result) => {
        if (err) return res.sendErr(err)
        if (result.affectedRows !== 1) return res.sendErr("订单信息更改失败!")

        res.send({
            status: 200,
            message: "订单信息更改成功!",
        })
    })
}


module.exports = {
    getOrderList,
    getOrderTotalNum,
    editOrderInfo
}